package com.kaesun.ufit.weight;

import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.kaesun.ufit.hardware.Buzzer;
import com.kaesun.ufit.tools.CalibrationView;

public class CalibrationActivity extends Activity implements View.OnClickListener, IOnHandlerMessage {

	private static final int BUTTON_IDS[] = {
		R.id.button_start, R.id.button_exit
	};

	private MainApplication mApp = null;
	private WeakRefHandler mHandler = null;

	private RelativeLayout mRelativeLayout = null;
	private CalibrationView mCalibrationView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calibration);

		for (int i=0; i<BUTTON_IDS.length; i++) {
			findViewById(BUTTON_IDS[i]).setOnClickListener(this);
		}

		mApp = (MainApplication)getApplication();
		mHandler = new WeakRefHandler((IOnHandlerMessage)this);

		mRelativeLayout = (RelativeLayout)findViewById(R.id.layout_buttons);
		mCalibrationView = (CalibrationView)findViewById(R.id.view_calibration);
		mCalibrationView.setContext(this);
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();
	}

	@Override
	protected void onPause() {

		super.onPause();
	} 

	@Override
	protected void onResume() {
		mApp.setHandler(mHandler, true);

		super.onResume();
	}

	public void onClick(View arg0) {
		mApp.timeoutReset();

		Buzzer.delay(50);
		switch (arg0.getId()) {
		case R.id.button_start:
			mRelativeLayout.setVisibility(View.INVISIBLE);
			mCalibrationView.calbration();
			break;
		case R.id.button_exit:
			setResult(RESULT_OK);
			finish();
			break;
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		mApp.timeoutReset();

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			if (false == mCalibrationView.isCalibration()) {
				mRelativeLayout.setVisibility(View.INVISIBLE);
			}
			break;
		case MotionEvent.ACTION_UP:
			if (false == mCalibrationView.isCalibration()) {
				mRelativeLayout.setVisibility(View.VISIBLE);
			}
			break;
		}
		return mCalibrationView.touchEvent(event);
		//return super.onTouchEvent(event);
	}

	@Override
	public void handleMessage(Message msg) {
		switch (msg.what) {
		case MainApplication.HANDLER_TIMEOUT_ACTIVITY:
			setResult(RESULT_OK);
			finish();
			break;
		}
	}
}
